<template>
  <div class="cart-page">
    <div class="top-bar">
      <div class="fix-bar">
        <!-- <van-icon class="go-back" name="arrow-left" color="#fff" size="20" @click="onClickLeft"/> -->
        <span class="title">购物车</span>
        <span class="operate" @click="changeOperate">{{isOperate?'完成':'管理'}}</span>
      </div>
    </div>
    <store-scroller @onRefresh="onRefresh" @onInfinite="onLoad">
      <div class="content">
        <van-checkbox-group class="card-goods"  v-model="checkedGoods">

          <van-swipe-cell v-for="item in normalList" :key="item.id" :on-close="onClose" :name="item.id">

            <van-checkbox
              class="card-goods-item van-hairline--bottom"
              :name="item.id"
              icon-size="20px"
              checked-color="#ff4444">
              <cardItem :item="item">
                <van-stepper
                  slot="num-step"
                  :value="item.quantity"
                  integer
                  :max="item.limitState ? item.limitNum : item.maxNum" 
                  input-width="30px"
                  button-size="20px"
                  @minus="updataeQuantiry(item.quantity - 1, item)"
                  @plus="updataeQuantiry(item.quantity + 1, item)"
                  @blur="updataeQuantiry(item.quantity - 0, item)"
                  @change="(val) => onChangeNum(val, item)"
                />
              </cardItem>
            </van-checkbox>

            <template slot="right">
              <van-button square type="danger" text="删除" />
            </template>

          </van-swipe-cell>

          <div v-if="disableList&&disableList.length>0">
            <div class="disable-bar">已失效</div>

            <van-swipe-cell v-for="item in disableList" :key="item.id" :on-close="onClose" :name="item.id">

              <!-- <van-checkbox
                class="card-goods-item van-hairline--bottom"
                :name="item.id"
                disabled
                icon-size="16px"
                checked-color="#ff4444"> -->
                <cardItem :item="item">
                  <van-stepper
                    slot="num-step"
                    :value="item.quantity"
                    :max="item.maxNum"
                    integer
                    disabled
                    input-width="26px"
                    button-size="20px"
                  />
                </cardItem>
              <!-- </van-checkbox> -->
              
              <template slot="right">
                <van-button square type="danger" text="删除" />
              </template>

            </van-swipe-cell>

          </div>
        </van-checkbox-group>
      </div>
    </store-scroller>
    <van-submit-bar
      v-show="!isOperate"
      class="submit-bar"
      :class="{noBot:this.$route.meta.single}"
      :safe-area-inset-bottom="true"
      :price="totalPrice"
      :disabled="!checkedGoods.length"
      :button-text="'结算'+selectCount"
      @submit="onSubmit"
    >
      <van-checkbox
        icon-size="20px"
        checked-color="#ff4444"
        v-model="isSelectAll"
        @change="changeAll"
      >全选</van-checkbox>
    </van-submit-bar>
    <div 
    class="operate-bar" 
    v-show="isOperate"
    :class="{noBot:this.$route.meta.single}"
    >
      <van-checkbox
        icon-size="20px"
        checked-color="#ff4444"
        v-model="isSelectAll"
        @change="changeAll"
      >全选</van-checkbox>
      <div class="white"></div>
      <button
        class="btn"
        :disabled="!checkedGoods.length"
        :class="{'disable_btn':!checkedGoods.length}"
        @click="deleteItem"
      >删除{{selectCount}}</button>
    </div>
    <store-loding v-show="loding"></store-loding>
  </div>
</template>
<script>
import Vue from 'vue'
import storeScroller from '@/components/store-scroller'
import cardItem from './cartItem'
import { Checkbox, CheckboxGroup, Stepper, SubmitBar, Toast, Icon, SwipeCell, Button, Dialog } from 'vant'
import { mapActions, mapGetters } from 'vuex'
import storeLoding from '@/components/store-loding'
Vue.use(Checkbox)
  .use(CheckboxGroup)
  .use(Stepper)
  .use(SubmitBar)
  .use(Toast)
  .use(Icon)
  .use(SwipeCell)
  .use(Button)
  .use(Dialog)

export default {
  components: {
    storeScroller,
    cardItem,
    storeLoding
  },
  data() {
    return {
      isOperate: false,
      checkedGoods: [],
      isSelectAll: false,
      loding: false
    }
  },
  mounted() {
    this.getCartList()
  },
  computed: {
    ...mapGetters('cart',['normalList','disableList']),
    /******** 删除(数量) ********/
    selectCount() {
      const count = this.checkedGoods.length
      if (count == this.normalList.length && count != 0) {
        this.isSelectAll = true
      } else {
        this.isSelectAll = false
      }
      return count ? `(${count})` : ''
    },
    /******** 合计 ********/
    totalPrice() {
      return this.normalList.reduce(
        (total, item) =>
          total +
          (this.checkedGoods.indexOf(item.id) !== -1
            ? item.price * item.quantity
            : 0),
        0
      ) * 100
    }
  },

  methods: {
    ...mapActions('cart', ['getCartList']),
    // onClickLeft() {
    //   this.$router.go(-1);
    // },
    /******** 管理 ********/
    changeOperate() {
      this.isOperate = !this.isOperate
    },
    /******** 全选 ********/
    changeAll() {
      if (this.isSelectAll) {
        this.checkedGoods = this.normalList.map(item => item.id)
      } else {
        if (this.checkedGoods.length == this.normalList.length) {
          this.checkedGoods = []
        }
      }
    },
    formatPrice(price) {
      return price.toFixed(2)
    },
    /******** change时算合计 ********/
    onChangeNum(val, item) {
      item.quantity = val
    },
    /******** 加、减、失焦时，更新数量 ********/
    updataeQuantiry(quantity, item) {
      const params = {
        id: item.id,
        quantity
      }
      this.loding = true
      this.$http
        .post('/cartItem/updateQuantity', params)
        .finally(() => {
          this.loding = false
        })
    },
    /******** 结算 ********/
    onSubmit() {
      let sku = []
      this.normalList.forEach(element => {
        if (this.checkedGoods.includes(element.id)) {
          sku.push(element)
        }
      })
      this.$store.commit('order/SET_CONFIRM_ORDER_LIST', [...sku])
      this.$router.push({
        name: 'confirmOrder',
        query: {
          type: 'cart'
        }
      })
    },
    /******** 删除购物车商品 ********/
    deleteItem() {
      this.$http
        .post('/cartItem/delete', { ids: this.checkedGoods })
        .then(() => {
          Toast('删除成功')
          this.checkedGoods = []
          this.getCartList()
        })
        .catch(error => {
          Toast(error.message)
        })
    },
    /******** 删除失效商品 ********/
    deleteDisableItem(ids) {
      this.$http
        .post('/cartItem/delete', { ids })
        .then(() => {
          Toast('删除成功')
          this.getCartList()
        })
        .catch(error => {
          Toast(error.message)
        })
    },
    /******** 左滑删除事件 ********/
    onClose(clickPosition, instance, id) {
      switch (clickPosition) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close();
          break;
        case 'right':
          Dialog.confirm({
            message: '确定删除吗？'
          }).then(() => {
            let ids = [id.name]
            this.deleteDisableItem(ids)
          });
          break;
      }
    },
    onRefresh(done) {
      this.getCartList().finally(() => {
        if (done) done()
      })
    },
    onLoad(done) {
      if (done) done(true)
    }
  }
}
</script>

<style lang="scss">
.cart-page {
  padding-top: 76px;
  .fix-bar {
    position: fixed;
    width: 100vw;
    text-align: center;
    z-index: 10;
    background: $red;
    height: 66px;
    padding-top: 35px;
    top: 0;
    .title {
      font-size: 16px;
      color: #fff;
    }
    // .go-back{
    //   position: absolute;
    //   left: 15px;
    // }
    .operate {
      color: #fff;
      position: absolute;
      right: 15px;
      font-size: 14px;
    }
  }

  .store-scroller {
    .van-pull-refresh {
      padding-bottom: 100px;
      min-height: calc(100vh - 176px)
    }
    .scroll {
      padding-top: 76px;
      ._v-content {
        padding-bottom: 100px;
      }
    }
  }
  .content {
    background-color: #fff;
    border-radius: 5px;
    overflow: hidden;
    .card-goods-item{
      align-items: center;
      padding: 0 10px;
    }
    /deep/ .van-card {
      background: transparent;
      width: 100%;
    }
    /deep/ .van-checkbox__label {
      width: 100%;
    }
    .van-button--normal{
      height: 100%
    }
    .van-card__price {
      color: #f44;
    }
    .disable-bar{
      font-size: 14px;
      color: #999;
      padding: 15px 0 15px 15px;
    }
  }
  .van-submit-bar {
    .van-checkbox {
      margin-left: 15px;
    }
  }
  .submit-bar{
    bottom: 50px;
    &.noBot{
      bottom: 0;
    }
  }
  .operate-bar {
    position: fixed;
    bottom: 50px;
    left: 0;
    z-index: 100;
    width: 100%;
    background-color: #fff;
    -webkit-user-select: none;
    user-select: none;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 14px;
    &.noBot{
      bottom: 0;
    }
    .van-checkbox {
      margin-left: 15px;
    }
    .white {
      flex: 1;
    }
    .btn {
      width: 110px;
      color: #fff;
      background-color: #f44;
      border: 1px solid #f44;
      height: 50px;
      line-height: 48px;
      font-size: 16px;
      text-align: center;
      &.disable_btn {
        opacity: 0.5;
      }
    }
  }
}
</style>
